<template>
  <div>
    <el-form ref="deptForm" :model="deptForm" label-width="100px" :rules="rules">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="deptForm.name" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="deptForm.code" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="deptForm.manager" placeholder="部门负责人">
          <el-option
            v-for="item in employees"
            :key="item.id"
            :label="item.username"
            :value="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="deptForm.introduce" type="textarea" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">确定</el-button>
        <el-button @click="onCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getSimplelist, addDepartment, getDeptDetail, editDeptDetail } from '@/api/departments'
export default {
  name: 'DeptDialog',
  props: {
    pid: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    },
    originList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    const validName = (rule, value, callback) => {
      // 添加子部门,子部门名称不能重复
      let existNameList = this.originList.filter(item => item.pid === this.pid).map(item => item.name)
      if (this.isEdit) {
        // 编辑时比较的是同级部门间的验证
        const dept = this.originList.find(item => item.id === this.pid)
        existNameList = this.originList.filter(item => item.pid === dept.pid && item.id !== this.pid)
          .map(item => item.name)
      }
      existNameList.includes(value) ? callback(new Error(`部门名称 ${value} 已经存在`)) : callback()
    }
    const valiCode = (rule, value, callback) => {
      // 添加子部门,验证所有部门的编码与当前添加子部门的code是否有重复
      let existCodeList = this.originList.map(item => item.code)
      if (this.isEdit) {
        // 编辑时:将所有部门的id与当前编辑的部门比较筛选,去除当前部门
        existCodeList = this.originList.filter(item => item.id !== this.pid).map(item => item.code)
      }
      existCodeList.includes(value) ? callback(new Error(`部门编码 ${value} 已经存在`)) : callback()
    }
    return {
      deptForm: {
        code: '',
        introduce: '',
        manager: '',
        name: ''
      },
      // 验证规则
      rules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入部门编码', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' },
          { validator: valiCode, trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '请输入部门介绍', trigger: 'blur' },
          { min: 1, max: 150, message: '长度在 1 到 150 个字符', trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '请输入部门负责人', trigger: 'change' }
        ]

      },
      employees: []
    }
  },
  created() {
    this.getSimplelist()
    this.getDeptDetail()
  },
  methods: {
    // 获取员工简单列表
    async getSimplelist() {
      const res = await getSimplelist()
      this.employees = res.data
    },
    // 添加部门
    async addDepartment() {
      const res = await addDepartment({ ...this.deptForm, pid: this.pid })
      this.$message.success(res.message)
      this.$emit('update-dept')
    },
    // 部门详情
    async getDeptDetail() {
      if (this.isEdit) {
        const res = await getDeptDetail(this.pid)
        // console.log(res)
        // 此处返回来的数据包含部门id信息,后面编辑部门可以直接传入id值
        this.deptForm = res.data
      }
    },
    // 编辑部门
    async editDeptDetail() {
      // console.log(this.deptForm)
      const res = await editDeptDetail(this.deptForm)
      console.log(res)
      this.$message.success(res.message)
      this.$emit('update-dept')
    },
    // 新增或编辑
    onSubmit() {
      // 兜底验证
      this.$refs.deptForm.validate(valid => {
        if (!valid) return
        this.isEdit ? this.editDeptDetail() : this.addDepartment()
      })
    },
    onCancel() {
      this.$emit('close')
    }
  }
}
</script>

<style lang="scss" scoped>
.el-form {
  padding: 5px 70px 5px 30px;
}
.el-select {
  width: 100%;
}
</style>
